/**
 * 证据管理
 */
$(function () {
    Evidence.init();
});

var Evidence = {
    init: function () {
        var me = this;
        me.pageSize = 30;//初始化显示30条
        me.vehicleIdListForClickMore = '';//初始化把需要点击更多功能的id存放
        me.exportVehicleId = '';
        me.alarmTypeMap = new HashMap();
        me.initAlarmTypeMap();
        me.initEvent();
        me.initVehicleList();
        me.initQueryTime();
        me.initVehicleUnitList();
        me.picCharts = this.initCharts();
        me.pic();
        Evidence.currentQueryParamsMap = new HashMap();   //储存查询参数
        $("#eventCode").select2();
        MapTool.init();
    },
    initEvent: function () {
        var me = this;
        $("#queryBtn").click(function () {
            //debugger;
            var startTime = $("#inputStartDate").val();
            var endTime = $("#inputEndDate").val();
            var startTimeSub = startTime.substr(0, 7);
            var endTimeTimeSub = endTime.substr(0, 7);
            if (startTimeSub != endTimeTimeSub) {
            	global.ajaxLoading.pop("不能跨月查询", true, 2000);
                return;
            }
            if (endTime < startTime) {
            	global.ajaxLoading.pop("结束时间不能小于开始时间", true, 2000);
                return;
            }

            $('#imageLable').html('');
            me.queryChartData();

        });
        //点击跳转将查询图片后可以选择需要打印的图片
        $('#exportBtn').click(function () {
            //window.print();
            //global.ajaxLoading.pop('正在查询中,请稍候!',true);
            $('.slider').hide();
            $('.content').addClass('marginL0');
            $("#moreRows").hide();
            $('#imageLable').find('.page:last').removeClass('pageAlways');
            window.print();
            $('.content').removeClass('marginL0');
            $('.slider').show();
            $("#moreRows").show();
            $('#imageLable').find('.page:last').addClass('pageAlways');
            //global.ajaxLoading.close();
        });
    },

    initEmptyVehicleList: function () {
        $('#vehicleSelDiv').html("<select class='query-select' id='selectVehicleSel'></select>");
        var selectStr = "";
        selectStr += "<option value=''>请选择/option>";
        $('#selectVehicleSel').html(selectStr);
        $("#selectVehicleSel").select2();
    },
    initCharts: function () {
        var me = this;
        var option = {
            color: ['#3398DB'],
            tooltip: {
                trigger: 'axis',
                show: true,
                axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                    show: false,
                    type: 'none'        // 默认为直线，可选为：'line' | 'shadow'
                },
                formatter: function (a) {
                    if (a[0].name == '') {
                        return;
                    }
                    var relVal = "";
                    relVal = a[0].name + "：" + a[0].value + "张";
                    return relVal;
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                containLabel: true
            },
            xAxis: [
                {
                    type: 'category',
                    //nameRotate : 135,
                    data: [],//['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
                    axisTick: {
                        alignWithLabel: true
                    },
                    axisLabel: {

                        textStyle: {
                            //color: 'blue',
                            //fontFamily: 'sans-serif',
                            fontSize: 10
                            //fontStyle: 'italic',
                            //fontWeight: 'bold'
                        }
                    }
                }
            ],
            yAxis: [
                {
                    type: 'value'
                }
            ],
            series: [
                {
                    name: '',
                    type: 'bar',
                    //barWidth: '60%',
                    barWidth: 20,//柱子宽度
                    //barCategoryGap:20,
                    itemStyle: {
                        normal: {
                            //color: 'tomato',
                            //barBorderColor: 'tomato',
                            //barBorderWidth: 6,
                            //barBorderRadius:0,

                        }
                    },
                    data: [],//[10, 52, 200, 334, 390, 330, 220]
                }
            ],
            dataZoom: [{
                type: 'inside',
                start: 0,
                end: 100
            }, {
                start: 0,
                end: 100,
                fillerColor: '#A3E1A3',
                handleColor: '#83A7D1'
            }]
        };

        var myChart = echarts.init(document.getElementById('myCharts'));
        myChart.setOption(option);
        window.onresize = myChart.resize;

        myChart.on('click', function (param) {
            global.ajaxLoading.pop('正在拼命加载,请稍候!', true);
            var vehicleIdList = me.vehicleIdList;
            var vehicleId = vehicleIdList[param.dataIndex];
            Evidence.exportVehicleId = vehicleId;
            me.vehicleIdListForClickMore = vehicleId;//在加载的时候把点击选中的柱状图车辆id赋值到全局变量
            me.queryPicListByVehicleId(vehicleId);
        });

        return {
            refash: function (option) {
                myChart.setOption(option);
            },
            option: option,
            picChartDom: myChart
        };

    },
    initVehicleUnitList: function () {
        var me = this;
        $.ajax({
            type: 'post',
            async: false,
            url: appCtx + "/system/common/loadUserUnit.html",
            cache: false,
            dataType: "JSON",
            success: function (data) {
                if (data) {
                    var selectStr = "<option value=''>请选择</option>";
                    for (var i = 0; i < data.length; i++) {
                        selectStr += "<option value='" + data[i].entId + "'>" + data[i].entName + "</option>";
                    }
                    $('#selectVehicleUnitSel').html(selectStr);
                    $("#selectVehicleUnitSel").select2();
                    $("#selectVehicleUnitSel").change(function () {
                        var entId = $(this).children('option:selected').val();
                        if (entId != '' && entId != null) {
                            me.initVehicleList(entId);
                        } else {
                            me.initVehicleList();
                        }
                    });
                }
            }
        });
    },
    queryChartData: function () {
        //debugger;
        var me = this;
        var startTime = $("#inputStartDate").val();
        var endTime = $("#inputEndDate").val();
        var unitId = $("#selectVehicleUnitSel").val();
        var vehicleID = $("#selectVehicleSel").val();
        var eventCode = $("#eventCode").val();
        Evidence.currentQueryParamsMap.put("unitId", unitId);
        Evidence.currentQueryParamsMap.put("eventCode", eventCode);
        $.ajax({
            type: 'post',
            async: false,
            url: appCtx + "/picture/queryEvidenceChartData.html?vehicleID=" + vehicleID + "&startTime=" + startTime + "&endTime=" + endTime + "&enterprisseId=" + unitId + "&eventCode=" + eventCode,
            cache: false,
            dataType: "JSON",
            success: function (data) {
                if (data) {
                    var option = me.picCharts.option;
                    option.xAxis[0].data = data.xAxisData;//['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
                    option.series[0].data = data.series;//[10, 52, 200, 334, 390, 330, 220];
                    me.picCharts.refash(option);
                    me.vehicleIdList = data.vehicleIdList;
                    me.startTime = startTime;
                    me.endTime = endTime;
                    me.eventCode = eventCode;
                    me.vehicleIdListForClickMore = data.vehicleIdList;//初始化的时候把车辆的ids放在全局变量
                    Evidence.exportVehicleId = data.vehicleIdList[0];
                    //me.queryPicListByVehicleId(data.vehicleIdList[0]);
                    if (data.vehicleIdList == "" || data.vehicleIdList == null) {
                        global.ajaxLoading.pop("无数据", false, 2000);
                        //$("#moreRows").hide();
                        return;
                    } else {
                        me.queryPicListByVehicleId(data.vehicleIdList);
                        $("#moreRows").show();
                    }
                }
            }
        });
    },
    /*初始化报警类型Map*/
    initAlarmTypeMap: function () {
        $.ajax({
            type: 'post',
            // async: false,
            url: appCtx + "/picture/getAlarmTypeForInitMap.html",
            cache: false,
            dataType: "JSON",
            success: function (data) {
                if (data) {
                    for (var i = 0; i < data.length; i++) {
                        Evidence.alarmTypeMap.put(data[i].id,data[i].name);
                    }
                }
            }
        });
    },
    changeType: function (id) {
        var alarmType = null;
        switch (id) {
            case 4 :
            case 51:
                alarmType = '打哈欠';
                break;
            case 5:
            case 60:
                alarmType = '打电话';
                break;
            case 6:
            case 61:
                alarmType = '抽烟';
                break;
            case 7:
            case 50:
                alarmType = '闭眼';
                break;
            case 8:
            case 62:
                alarmType = '注意力分散';
                break;
            case 9:
            case 65:
                alarmType = '急减速';
                break;
            case 10:
            case 64:
                alarmType = '急加速';
                break;
            case 13:
            case 41:
            case 42:
                alarmType = '车道偏离报警触发';
                break;
            case 14:
            case 40:
                alarmType = '前向碰撞报警触发';
                break;
            default:
                alarmType = '';
        }
        return alarmType;
    },
    queryPicListByVehicleId: function (vehicleIdList) {
        var me = this;
        //var startTime=me.startTime + " 00:00:00";
        //var endTime=me.endTime + " 23:59:59";
        $.ajax({
            type: 'post',
            /*async : false,*/
            url: appCtx + "/picture/queryPictureOrVedioList.html?vehicleID=" + vehicleIdList + "&startTime=" + me.startTime + "&endTime=" + me.endTime + "&eventCode=" + me.eventCode,
            cache: false,
            dataType: "JSON",
            success: function (data) {
                if (data) {
                    me.initPicListHtml(data);
                } else {
                    $('.carousel-inner').html('');
                }
                global.ajaxLoading.close();
            }
        });
    },
    /**
     * 初始化20张图片
     * @param list
     */
    initPicListHtml: function (list) {
        //debugger;
        var me = this;
        me.picList = null;
        $('#imageLable').html('');
        me.pageSize = 20;//每次重新查询的时候都初始化为20条
        var html = '';
        //html+='<div>';
        var len = list.length;
        //var html = '<div class="page">';
        var html = '<div class="page clearfix pageAlways">';
        for (var i = 0; i < len; i++) {
            //var gpsSpeed = Math.round(list[i].gpsSpeed);
            var address = Evidence.showAddress(i, list[i].coordinates.coordinates[0], list[i].coordinates.coordinates[1]);
            if (i < len - 1) {
                html += '<div class="oneWarp">';
                html += '<div class="one">';
                html += '<div class="one-top"><a class="db imgA largeImg pr" style="border:none;" href="javascript:void(0);" index="' + i + '" vehicleId="' + list[i].vehicle_id + '"  imgSrc=' + list[i].imgUrl + '><div class="imgD"></div><img class="pa" src="' + list[i].imgUrl + '" style="width: 100%"></a></div>';
                /*if (list[i].mediaFormat == 0) {
                    html += '<div class="one-top"><a class="db imgA largeImg pr" style="border:none;" href="javascript:void(0);" index="' + i + '" vehicleId="' + list[i].vehicle_id + '"  imgSrc=' + list[i].imgUrl + '><div class="imgD"></div><img class="pa" src="' + list[i].imgUrl + '" style="width: 100%"></a></div>';
                } else if (list[i].mediaFormat == 5) {
                    html += '<div class="one-top"><a class="db imgA largeImg pr largeVideoCls" style="border:none;" href="javascript:void(0);" index="' + i + '" vehicleId="' + list[i].vehicle_id + '"  imgSrc=' + list[i].imgUrl + '><div class="imgD"></div><img class="pa" src=' + appCtx + '/resources/images/video/playIcon.png ><video  src=" ' + list[i].imgUrl + '.mp4"></video></a></div>';
                }*/
                html += '<div class="one-bottom"><span>车牌号码: ' + list[i].vehicle_no + '</span><br><span>行车速度: ' + list[i].gps_speed + ' KM/H</span><br><span>报警类型: ' + Evidence.alarmTypeMap.get(list[i].eventCode) + '</span><br><span>拍照时间: ' + list[i].gpsTimeStr + '</span><br><span id=span' + i + '></span></div>';
                html += '</div></div>';
            } else if (i == len - 1) {
                html += '<div class="oneWarp">';
                html += '<div class="one">';
                html += '<div class="one-top"><a class="db imgA largeImg pr" style="border:none;" href="javascript:void(0);" index="' + i + '" vehicleId="' + list[i].vehicle_id + '"  imgSrc=' + list[i].imgUrl + '><div class="imgD"></div><img class="pa" src="' + list[i].imgUrl + '" style="width: 100%"></a></div>';
                /* if (list[i].mediaFormat == 0) {
                     html += '<div class="one-top"><a class="db imgA largeImg pr" style="border:none;" href="javascript:void(0);" index="' + i + '" vehicleId="' + list[i].vehicle_id + '"  imgSrc=' + list[i].imgUrl + '><div class="imgD"></div><img class="pa" src="' + list[i].imgUrl + '" style="width: 100%"></a></div>';
                 } else if (list[i].mediaFormat == 5) {
                     html += '<div class="one-top"><a class="db imgA largeImg pr largeVideoCls" style="border:none;" href="javascript:void(0);" index="' + i + '" vehicleId="' + list[i].vehicle_id + '"  imgSrc=' + list[i].imgUrl + '><div class="imgD"></div><img class="pa" src=' + appCtx + '/resources/images/video/playIcon.png ></a></div>';
                 }*/
                html += '<div class="one-bottom"><span>车牌号码: ' + list[i].vehicle_no + '</span><br><span>行车速度: ' + list[i].gps_speed + ' KM/H</span><br><span>报警类型: ' + Evidence.alarmTypeMap.get(list[i].eventCode) + '</span><br><span>拍照时间: ' + list[i].gpsTimeStr + '</span><br><span id=span' + i + '></span></div>';
                html += '</div></div>';
                html += '</div>';
            } else {
                html += '<div class="oneWarp">';
                html += '<div class="one">';
                html += '<div class="one-top"><a class="db imgA largeImg pr" style="border:none;" href="javascript:void(0);" index="' + i + '" vehicleId="' + list[i].vehicle_id + '"  imgSrc=' + list[i].imgUrl + '><div class="imgD"></div><img class="pa" src="' + list[i].imgUrl + '" style="width: 100%"></a></div>';
                /*if (list[i].mediaFormat == 0) {
                    html += '<div class="one-top"><a class="db imgA largeImg pr" style="border:none;" href="javascript:void(0);" index="' + i + '" vehicleId="' + list[i].vehicle_id + '"  imgSrc=' + list[i].imgUrl + '><div class="imgD"></div><img class="pa" src="' + list[i].imgUrl + '" style="width: 100%"></a></div>';
                } else if (list[i].mediaFormat == 5) {
                    html += '<div class="one-top"><a class="db imgA largeImg pr" style="border:none;" href="javascript:void(0);" index="' + i + '" vehicleId="' + list[i].vehicle_id + '"  imgSrc=' + list[i].imgUrl + '><div class="imgD"></div><img class="pa" src=' + appCtx + '/resources/images/video/playIcon.png ></a></div>';
                }*/

                html += '<div class="one-bottom"><span>车牌号码: ' + list[i].registrationNo + '</span><br><span>行车速度: ' + list[i].gpsSpeed + ' KM/H</span><br><span>报警类型: ' + Evidence.alarmTypeMap.get(list[i].eventCode) + '</span><br><span>拍照时间: ' + list[i].gpsTimeStr + '</span><br><span id=span' + i + '></span></div>';
            }
        }
        //if(len==20){
        html += '</div>';
        //}
        me.picList = list;
        $('#imageLable').html(html);
        //var imgW = $("#imageLable").find('.largeImg').width();
        //$("#imageLable").find('.largeImg').height(imgW*0.75);
        if (list.length < 20) {
            $("#moreRows").hide();
        } else {
            $("#moreRows").show();
        }
    },
    /**
     * 点击更多图片
     */
    clickPicListHtml: function (list) {
        var me = this;
        var htmlForClick = '<div class="page clearfix pageAlways">';
        for (var i = 0; i < list.length; i++) {
            var id = me.pageSize + i;
            var address = Evidence.showAddress(id, list[i].coordinates.coordinates[0], list[i].coordinates.coordinates[1]);
            htmlForClick += '<div class="oneWarp">';
            htmlForClick += '<div class="one">';
            htmlForClick += '<div class="one-top"><a class="db imgA largeImg pr" href="javascript:void(0);" index="' + id + '" vehicleId="' + list[i].vehicle_id + '"  imgSrc=' + list[i].imgUrl + '><div class="imgD"></div><img class="pa" src="' + list[i].imgUrl + '" style="width: 100%"></a></div>';
            /*if (list[i].mediaFormat == 0) {
                htmlForClick += '<div class="one-top"><a class="db imgA largeImg pr" href="javascript:void(0);" index="' + id + '" vehicleId="' + list[i].vehicle_id + '"  imgSrc=' + list[i].imgUrl + '><div class="imgD"></div><img class="pa" src="' + list[i].imgUrl + '" style="width: 100%"></a></div>';
            } else if (list[i].mediaFormat == 5) {
                htmlForClick += '<div class="one-top"><a class="db imgA largeImg pr largeVideoCls" style="border:none;" href="javascript:void(0);" index="' + id + '" vehicleId="' + list[i].vehicle_id + '"  imgSrc=' + list[i].imgUrl + '><div class="imgD"></div><img class="pa" src=' + appCtx + '/resources/images/video/playIcon.png ></a></div>';
            }*/
            htmlForClick += '<div class="one-bottom"><span>车牌号码: ' + list[i].vehicle_no + '</span><br><span>行车速度: ' + list[i].gps_speed + ' KM/H</span><br><span>报警类型: ' + Evidence.alarmTypeMap.get(list[i].eventCode) + '</span><br><span>拍照时间: ' + list[i].gpsTimeStr + '</span><br><span id=span' + id + '></span></div>';
            htmlForClick += '</div></div>';
            me.picList.push(list[i]);//将点击更多的元素添加到图片集合
        }
        htmlForClick += '</div>';
        //me.picList = list;
        $('#imageLable').append(htmlForClick);
        me.pageSize = me.pageSize + 30;
        //var imgW = $("#imageLable").find('.largeImg').width();
        //$("#imageLable").find('.largeImg').height(imgW*0.75);
        if (list.length < 30) {
            $("#moreRows").hide();
        } else {
            $("#moreRows").show();
        }
        global.ajaxLoading.close();
    },
    /**
     * 高德你地理解析地址 hkj
     * @param id
     * @param start_lon
     * @param start_lat
     */
    showAddress: function (id, start_lon, start_lat) {
        var ctrl = "#span" + id;
        var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
        });
        geocoder.getAddress(new AMap.LngLat(start_lon, start_lat), function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
                var address = result.regeocode.formattedAddress;
                $(ctrl).html('拍照地址:' + address);
                //$(ctrl).attr('title',address);
                //$(ctrl).css('color','#666');
            } else {
                $(ctrl).html("无地址信息");
            }
        });
    },
    /**
     * 加载更多图片
     * @param tbId
     */
    morePictureList: function () {
        //debugger;
        global.ajaxLoading.pop('正在加载中,请稍候!', true);

        var me = this;
        var listForVehicle = Evidence.vehicleIdListForClickMore;
        var unitId = Evidence.currentQueryParamsMap.get("unitId");
        var eventCode = Evidence.currentQueryParamsMap.get("eventCode");
        $.ajax({
            type: 'post',
            /*async : false,*/
            url: appCtx + "/picture/queryPicListByVehicleIdForMore.html?vehicleId=" + listForVehicle + "&startTime=" + me.startTime + "&endTime=" + me.endTime + "&pageSize=" + me.pageSize + "&enterprisseId=" + unitId + "&eventCode=" + eventCode,
            cache: false,
            dataType: "JSON",
            success: function (data) {
                if (data) {
                    //me.pageSize = me.pageSize+30;
                    me.clickPicListHtml(data);
                } else {
                    $('.carousel-inner').html('');
                }
                //global.ajaxLoading.close();
            }
        });

    },
    //车辆树加载
    initVehicleList: function (entId) {
        var urlTemp;
        if (entId) {
            urlTemp = "/system/common/loadUserVehicle.html?enterprise_id=" + entId;
        } else {
            urlTemp = "/system/common/loadUserVehicle.html";
        }
        $.ajax({
            type: 'post',
            async: false,
            url: appCtx + urlTemp,
            cache: false,
            dataType: "JSON",
            success: function (data) {
                if (data) {
                    $('#vehicleSelDiv').html("<select class='query-select' id='selectVehicleSel'></select>");
                    var selectStr = "";
                    selectStr += "<option value=''>请选择车辆</option>";
                    $.each(data, function (entryIndex, entry) {
                        selectStr += "<option value='" + entry.id + "'>" + entry.vehicle_no + "</option>";
                    });

                    $('#selectVehicleSel').html(selectStr);

                    $("#selectVehicleSel").select2();

                }
            }
        });
    },
    initQueryTime: function () {//默认时间
        var todayDate = new Date();
        var todayDateStr = todayDate.getFullYear() + "-" + (todayDate.getMonth() + 1) + "-" + todayDate.getDate();
        //$("#inputEndDate").val(todayDateStr);

        var nowDate = new Date();
        //var beforeDate = new Date(todayDate-86400000*1); //前一天
        var yyyy = nowDate.getFullYear(), mm = (nowDate.getMonth() + 1).toString(), dd = nowDate.getDate().toString();

        var h = nowDate.getHours();
        h = h < 10 ? ('0' + h) : h;
        var minute = nowDate.getMinutes();
        minute = minute < 10 ? ('0' + minute) : minute;
        var second = nowDate.getSeconds();
        second = second < 10 ? ('0' + second) : second;


        if (mm.length == 1) {
            mm = '0' + mm;
        }
        if (dd.length == 1) {
            dd = '0' + dd;
        }
        $("#inputStartDate").val(yyyy + '-' + mm + '-' + dd + " 00:00:00");
        $("#inputEndDate").val(yyyy + '-' + mm + '-' + dd + " " + h + ':' + minute + ':' + second);
        //$("#inputEndDate").val(yyyy + '-' + mm + '-' + dd+" 23:59:59");
    },
    /**
     * 图片切换
     */
    pic: function () {
        var me = this;
        var arr = [0];
        var index = 0;
        var length = 0;
        //$('#myCarousel').rebox({ selector: '.imgA' });
        $('#allTable').on('slide.bs.carousel', function (event) {
            var $hoder = $('#allTable').find('.item'),
                $items = $(event.relatedTarget);
            //getIndex就是轮播到当前位置的索引
            var getIndex = $hoder.index($items);
            if (arr.indexOf(getIndex) == -1) {
                arr.push(getIndex);
                //加载图片
            }
        });
        $('#allTable').on('click', '.imgA', function (e) {
            e.preventDefault();
            index = JSON.parse($(this).attr('index'));
            var picObj = me.picList[index];
            var src = picObj.imgUrl;
            /*if (picObj.mediaFormat == 5) {
                $("#largeImgage").css("display", "none");
                $("#largeVideo").css("display", "block");
                $('#largeVideo').attr('src', src + ".mp4");
            } else if (picObj.mediaFormat == 0) {
            }*/
            $(" #largeVideo").css("display", "none");
            $(" #largeImgage").css("display", "block");
            $('#largeImgage').attr('src', src);
            //var picIndex= JSON.parse($(this).attr('index'));
            length = $('#allTable').find('.imgA').length;

            $('.largeImgPop,#mask').show();
            $('.pageSize.pa').html(index + 1 + '/' + length);
            if (length == 1) {
                $('.prevNext').hide();
            }
            //地图信息
            MapTool.loadMapData(picObj);

        });

        $('.largeImgPop').find('.close').click(function () {
            $('.largeImgPop,#mask').hide();
            $('#largeImgage').attr('src', '');
        });


        $('.largeImgPop').find('.prev').click(function () {
            if (index === 0) {
                index = length - 1;
            } else {
                index--;
            }
            var picObj = me.picList[index];
            var src = picObj.imgUrl;
            /*if (picObj.mediaFormat == 5) {
                $("#largeImgage").css("display", "none");
                $("#largeVideo").css("display", "block");
                $('#largeVideo').attr('src', src + ".mp4");
            } else if (picObj.mediaFormat == 0) {
            }*/
            $(" #largeVideo").css("display", "none");
            $(" #largeImgage").css("display", "block");
            $('#largeImgage').attr('src');
            /*var display = $('.largeImgPop').find('.next').css('display');
            if(display=='none'){
                $('.largeImgPop').find('.next').show();
            }*/
            var src = $('#allTable').find('.imgA').eq(index).attr('imgSrc');
            $('#largeImgage').attr('src', src);
            var picObj = me.picList[index];
            MapTool.loadMapData(picObj);
            $('.pageSize.pa').html(index + 1 + '/' + length);
        });

        $('.largeImgPop').find('.next').click(function () {
            if (index === length - 1) {
                index = 0;
            } else {
                index++;
            }
            var picObj = me.picList[index];
            var src = picObj.imgUrl;
            /* if (picObj.mediaFormat == 5) {
                 $("#largeImgage").css("display", "none");
                 $("#largeVideo").css("display", "block");
                 $('#largeVideo').attr('src', src + ".mp4");
             } else if (picObj.mediaFormat == 0) {
             }*/
            $(" #largeVideo").css("display", "none");
            $(" #largeImgage").css("display", "block");
            $('#largeImgage').attr('src', src);
            /*var display = $('.largeImgPop').find('.prev').css('display');
            if(display=='none'){
                $('.largeImgPop').find('.prev').show();
            }*/
            var src = $('#allTable').find('.imgA').eq(index).attr('imgSrc');
            $('#largeImgage').attr('src', src);
            var picObj = me.picList[index];
            MapTool.loadMapData(picObj);
            $('.pageSize.pa').html(index + 1 + '/' + length);
        });
    },
};
//时间位数为1位数时，前面补0
var setFormat = function (x) {
    if (x < 10) {
        x = "0" + x;
    }
    return x;
};
//获取从现在到 beforetime 小时前的时间（beforetime 只能是整数）
var beforeNowtime = function (beforetime) {
    var endTime = $("#inputEndDate").val();//获取日期框的值
    endTime = endTime.replace(/-/g, "/");

    var date = new Date(endTime); //日期对象
    date.setHours(date.getHours() - beforetime);
    var now = "";
    now = date.getFullYear() + "-"; //读英文就行了
    now = now + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';//取月的时候取的是当前月-1如果想取当前月+1就可以了
    now = now + setFormat(date.getDate()) + " ";
    now = now + setFormat(date.getHours()) + ":";
    now = now + setFormat(date.getMinutes()) + ":";
    now = now + setFormat(date.getSeconds()) + "";
    return now;
};

var MapTool = {
    init: function () {
        var me = this;
        me.oldVehicleId = 0;
        me.map = me.map();
    },
    /**
     * 地图渲染
     * */
    map: function () {
        var me = this;
        var map = new AMap.Map('mymap', {
            resizeEnable: true,
            zoom: 14,
            center: [113.645096, 23.631439]
        });
        return map;
    },
    /**
     * 增加覆盖物
     * @param map
     * @param lon
     * @param lat
     */
    addMarker: function (data) {
        var me = this;
        marker = new AMap.Marker({
            map: me.map,
            position: [data.gdLng, data.gdLat],
            icon: global.url.domain + "gps-web/resources/images/mapTool/car1.png",
            offset: new AMap.Pixel(-15, -10),
            autoRotation: true
        });

        this.initHashMap.GlobalMarkerCache.put(data.vehicleId, marker);
    },

    addInfoMarker: function (data) {
        var pathName = window.document.location.pathname;
        var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);//获取项目名
        var me = this;
        currentStatus = data.status ? "定位" : "盲区";
        var inter = "";
        var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)});
        MapTool.infoWindow = infoWindow;
        marker = new AMap.Marker({
            map: me.map,
            position: [data.longitude, data.latitude],
            icon: global.url.domain + projectName + "/resources/images/mapTool/car1.png",
            offset: new AMap.Pixel(-15, -10),
            autoRotation: true
        });
        if (data.internalNumber) {
            inter = data.internalNumber;
        }
        var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
        });
        geocoder.getAddress([data.longitude, data.latitude], function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
                var currentAddr = result.regeocode.formattedAddress;
                marker.content = '车牌号：' + data.registrationNo + '</br>拍照时间：' + data.gpsTime + '</br>车速：' + data.gpsSpeed + ' KM/H</br>状态：' + currentStatus + '<br/>' + '地点：<span id="address" name="address">' + currentAddr + '</span>';
                infoWindow.setContent(marker.content);
            } else {
                //获取地址失败
                marker.content = '车牌号：' + data.registrationNo + '</br>拍照时间：' + data.gpsTime + '</br>车速：' + data.gpsSpeed + ' KM/H</br>状态：' + currentStatus + '<br/>' + '地点：<span id="address" name="address"></span>';
                infoWindow.setContent(marker.content);
            }
        });
        marker.on('click', function (e) {
            // infoWindow.setContent(e.target.content + me.address);
            infoWindow.setContent(e.target.content);
            infoWindow.open(me.map, e.target.getPosition());
        });
        this.initHashMap.GlobalMarkerCache.put(data.vehicleId, marker);

        // infoWindow.setContent(marker.content);
        setTimeout(function () {
            infoWindow.open(me.map, marker.getPosition());
        }, 300);
        MapTool.getAddress(data);
    },
    /**
     * 设置地图中心点
     * @param data  定位数据
     */
    setCenter: function (data) {
        var me = this;
        me.map.setZoomAndCenter(14, new AMap.LngLat(data.longitude, data.latitude));
    },
    /**
     * 高德逆地址解析
     * @param ctrl  地址标签ID
     * @param  data 定位经纬度
     */
    getAddress: function (data) {
        var me = this;
        var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
        });
        geocoder.getAddress(new AMap.LngLat(data.gdLng, data.gdLat), function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
                var address = result.regeocode.formattedAddress;
                me.initHashMap.GlobalAddressCache.put(data.longitude + '_' + data.longitude, address);
                me.address = address;
                $("#address").html(address);
            }
        });

    },
    /*初始化各类数据，用于存储*/
    initHashMap: {
        GlobalMarkerCache: new HashMap(),      // 地图车辆缓存  key: Id value:marke
        GlobalAddressCache: new HashMap()
    },
    /**
     * 删除覆盖物
     * @param vid 车辆ID
     */
    clearMarker: function (vid) {
        var me = this;
        var marker = me.initHashMap.GlobalMarkerCache.get(vid);
        if (marker) {
            var infoWindow = MapTool.infoWindow;
            infoWindow.close();
            marker.setMap(null);
            marker = null;
        }
    },
    loadMapData: function (picObj) {
        var data = {
            longitude: picObj.coordinates.coordinates[0],
            latitude: picObj.coordinates.coordinates[1],
            gdLng: picObj.gdLng,
            gdLat: picObj.gdLat,
            vehicleId: picObj.vehicle_id,
            registrationNo: picObj.vehicle_no,
            gpsSpeed: picObj.gps_speed,
            gpsMileage: picObj.mileage,
            gpsTime: picObj.gpsTimeStr,
            // address: picObj.address,
            // internalNumber: picObj.internalNumber,
            status: picObj.status
        };
        MapTool.setCenter(data);
        MapTool.clearMarker(MapTool.oldVehicleId);
        //MapTool.getAddress(data);
        MapTool.addInfoMarker(data);
        MapTool.oldVehicleId = picObj.vehicleId;
    }
};
